angular.module('controllers',['ngPlugin'])
    .controller('formController',['$scope','$timeout','tinymceConfig','notify','$http','$state','$stateParams',function($scope,$timeout,tinymceConfig,notify,$http,$state,$stateParams){
        // 提交数据验证================================================
        function validateData(){
            var validate = {
                msg: '',
                flag: false
            },keep=true,count=0;
            if(!$scope.postData.name){
                validate.msg = '请输入活动名称';
            }else if($scope.postData.name&&$scope.postData.name.length>20){
                validate.msg = '活动名称最多不超过20个字符';
            }else if(!$scope.postData.start_time){
                validate.msg = '开始时间不能为空';
            }else if(!$scope.postData.end_time){
                validate.msg = '结束时间不能为空';
            }else if($scope.postData.start_time>$scope.postData.end_time){
                validate.msg = '结束时间不能小于开始时间';
            }else if(!$scope.postData.description){
                validate.msg = '活动简介不能为空';
            }else if($scope.channel.app.is_open=='on'&&$scope.channel.app.app_urls[0]&&!/^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test($scope.channel.app.app_urls[0])) {
                validate.msg = '请输入正确的链接（例如：http://www.chinamcloud.com）';
            }else if($scope.postData.shares.isopen=='on'){
                if(!$scope.postData.shares.title){
                    validate.msg = '分享标题不能为空';
                }else if(!$scope.postData.shares.content){
                    validate.msg = '分享内容不能为空';
                }else if(!$scope.postData.shares.thumb){
                    validate.msg = '分享图片不能为空';
                }else{
                    validate.flag = true;
                }
            }else{
                validate.flag = true;
            }
            return validate;
        }
        //图片上传配置
        $scope.fileConfig = {
            config: {
                language: 'zh',
                maxFileCount: 1,
                maxFileSize: 200,
            },
        }
        //富文本配置
        $scope.tinymceOptions = angular.extend({},tinymceConfig,{
            setup : function(ed) {
                ed.on('blur', function(e) {
                    // console.log(tinymce.activeEditor.getContent());
                });
            }
        });
        $scope.postData = {
            name: '',
            category: $scope.params['category'],
            start_time: '',
            end_time: '',
            model_id: $scope.params['model_id'],
            template_id: $scope.params['template_id'],
            background_img:  '',
            list_background_img: '',
            app_url: '',
            description: '',
            limits: {
                num: 1,
                type: 'day'
            },
            rules: {
                is_spot: false,
                address: '',
                longitude: 0,
                latitude: 0,
                range: 100
            },
            shares: {
                isopen: 'off',
                title: '',
                content: ''
            }
        }
        //切换tab
        $scope.toggleTab = function($event,index){
            if(!$scope.activity_id){
                notify('填写并保存内容设置',3);
            }else{
                $scope.tabIndex = index;
            }
        }
        //提交活动
        $scope.submit = function($event,callback){
            var $btn = angular.element($event.target);
            if(!$btn.hasClass('disabled')){
                var validate = validateData();
                if(!validate.flag){
                    notify(validate.msg,3);
                }else{
                    $scope.postData.validations = [];
                    angular.forEach($scope.controls,function(item,i){
                        if(item.checked){
                            $scope.postData.validations.push({
                                type: item.value,
                                password: item.password
                            });
                        }
                    });
                    $btn.addClass('disabled');
                    $http({
                        method: $scope.activity_id?'PATCH':'POST',
                        url: $scope.activity_id?'/web-api/activities/'+$scope.activity_id+'/quizzes':'/web-api/activity/quizzes',
                        headers:  JSON.parse($('meta[name="profile"]').attr('content')),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        data: $scope.postData,
                    }).then(function(httpData){
                        var data = httpData.data;
                        $btn.removeClass('disabled');
                        if(data.code==200){
                            notify('保存成功',2);
                            if($scope.tabIndex==1) {
                                $scope.tabIndex = 2;
                            }
                            if(!$scope.activity_id){
                                $scope.activity_id = data.data.id;
                            }
                            if(callback){
                                setTimeout(callback,2000);
                            }
                        }else{
                            notify(data.message,3);
                        }
                    },function(httpData){
                        var data = httpData.data;
                        $btn.removeClass('disabled');
                        notify(data.message,3);
                    });
                }
            }
        };
    }])